package com.huang.PC;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/*
*  阻塞队列 生产者消费者模式   不需要考虑什么时候 阻塞  什么时候唤醒 线程（阻塞队列内部写好了）
*   只要关心  是否生产 消费成功
*
* */
class zy{
    private  BlockingQueue<String> blockingQueue;
    private volatile boolean flag=true;

    public zy(BlockingQueue blockingQueue) {
        this.blockingQueue=blockingQueue;
    }

    public void con() throws Exception {
      while (flag){
          Object poll = blockingQueue.poll(2, TimeUnit.SECONDS);
          if(poll==null || poll=="") {
              System.out.println("消费失败了。。。" + poll);
          }else{
              System.out.println("消费成功了。。。。。"+poll);
          }
          TimeUnit.SECONDS.sleep(1);
      }
        System.out.println("老板叫停了。。。。");

  }

    public void pro() throws Exception {
        String mb="面包";
        while (flag){

            boolean offer = blockingQueue.offer(mb, 2, TimeUnit.SECONDS);
            if(offer) {
                System.out.println("生产了。。。" + mb);
            }else {
                System.out.println("生产失败了。。。" + mb);
            }
           TimeUnit.SECONDS.sleep(1);
        }
        System.out.println("老板叫停了。。。。");
    }

    public void stop(){
        flag=false;
        System.out.println("可以停止了。。。");
    }



}
public class BlockingqueuePC {
    public static void main(String[] args) throws InterruptedException {
        zy zy = new zy(new ArrayBlockingQueue<String>(10));



        new Thread(()->{
            try {
                zy.con();
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();


        new Thread(()->{
            try {
                zy.pro();
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }).start();


        TimeUnit.SECONDS.sleep(5);

        zy.stop();
    }
}
